<?php
namespace app\index\model;

use app\index\model\UserModel;
use think\Db;
use app\common\model\ToolModel;

class NewproductauditModel
{
    /**
     * 获取资料包/样品 审核列表数据
     * @author LSH
     * @return array
     */
    public static function dbGetManufactureList($param, $titles = null, $function = null)
    {
        $where = [];
        $where['a.type'] = $param['type']??1;
        $where['s.status'] = 1; // SKU状态为启用
        !empty($param['sku'])&&$where['a.sku'] = ['IN',explodeStr($param['sku'])];
        !empty($param['developer'])&&$where['t.developer'] = $param['developer'];
        !empty($param['returnpeople'])&&$where['a.return_people'] = $param['returnpeople'];
        !empty($param['buttman'])&&$where['a.butt_man'] = $param['buttman'];
        !empty($param['status'])&&$where['a.status'] = ['IN',explode(',', $param['status'])];
        !empty($param['time'])&&$where['h.creation_time'] = [['>=',substr($param['time'],0,10).' 00:00:00'], ['<=',substr($param['time'],-10,10).' 23:59:59'],'AND'];
        !empty($param['audittime'])&&$where['a.audit_time'] = [['>=',substr($param['audittime'],0,10).' 00:00:00'], ['<=',substr($param['audittime'],-10,10).' 23:59:59'],'AND'];
        !empty($param['returntime'])&&$where['a.return_time'] = [['>=',substr($param['returntime'],0,10).' 00:00:00'], ['<=',substr($param['returntime'],-10,10).' 23:59:59'],'AND'];
        !empty($param['handovertype'])&&$where['h.type'] = $param['handovertype'];

        $db = Db::table('manage_manufacture_audit')
            ->alias('a')
            ->join('skus s','a.sku = s.sku','LEFT')
            ->join('sku_attribute t','a.sku = t.sku','LEFT')
            ->join('sku_handover h','h.sku = a.sku','LEFT')
            ->field('
                a.id,
                a.sku,
                s.spu,
                s.name,
                h.type,
                h.remarks develop_remarks,
                h.creation_time,
                h.production_type_num,
                h.imitation,
                h.realpic,
                a.butt_man,
                a.status,
                CASE 
                    a.status 
                    WHEN 1 THEN "待审核"
                    WHEN 2 THEN "已审核"
                    WHEN 3 THEN "已驳回"
                    ELSE "" 
                END status_name,
                a.auditor,
                a.audit_time,
                a.remarks,
                a.sample_status,
                CASE 
                    a.sample_status 
                    WHEN 1 THEN "制作中"
                    WHEN 2 THEN "已归还"
                    ELSE "" 
                END sample_status_name,
                a.return_people,
                a.return_time,
                a.img_grade,
                CASE 
                    h.authorization
                    WHEN 0 THEN "未授权"
                    WHEN 1 THEN "已授权"
                    ELSE "" 
                END authorization_name,
                h.developer,
                h.develop_link,
                h.research_links,
                h.logo,
                h.quantity,
                h.quantity_unit,
                h.aslength,
                h.aswide,
                h.ashight,
                h.audit_remarks
            ');
        !empty($where)&&$db->where($where);
        $db->order('a.id','desc');
        return \app\common\service\ToolService::downOrReturn($db, $param, $titles, $function);
    }

    /**
     * 新品分派列表数据
     * @author LSH
     * @return array
     */
    public static function dbGetNewProductAssignInfo($param, $titles = null, $function = null)
    {
        $where = [];
        $where['s.status'] = 1; // SKU状态为启用
        !empty($param['sku'])&&$where['a.sku'] = ['IN',explodeStr($param['sku'])];
        !empty($param['developer'])&&$where['h.developer'] = $param['developer'];
        !empty($param['imgoperator'])&&$where['a.img_operator'] = $param['imgoperator'];
        !empty($param['describeoperator'])&&$where['a.edit_operator'] = $param['describeoperator'];
        !empty($param['assignstatus'])&&$where['a.assign_status'] = $param['assignstatus'];
        !empty($param['htype'])&&$where['h.type'] = ['LIKE','%'.$param['htype'].'%'];
        !empty($param['editgrade'])&&$where['a.edit_grade'] = ['LIKE','%'.$param['editgrade'].'%'];
        !empty($param['imggrade'])&&$where['a.img_grade'] = ['LIKE','%'.$param['imggrade'].'%'];
        if(!empty($param['editimgassign'])){
            if($param['editimgassign'] == 1 && empty($param['imgoperator'])) $where['a.img_operator'] = null;
            if($param['editimgassign'] == 2 && empty($param['imgoperator'])) $where['a.img_operator'] = ['<>',''];
            if($param['editimgassign'] == 3 && empty($param['describeoperator'])) $where['a.edit_operator'] = null;
            if($param['editimgassign'] == 4 && empty($param['describeoperator'])) $where['a.edit_operator'] = ['<>',''];
        } 
        !empty($param['productiontype'])&&$where['h.production_type'] = $param['productiontype'];
        !empty($param['editassigntime'])&&$where['a.edit_assign_time'] = [['>=',substr($param['editassigntime'],0,10).' 00:00:00'], ['<=',substr($param['editassigntime'],-10,10).' 23:59:59'],'AND'];
        !empty($param['imgassigntime'])&&$where['a.img_assign_time'] = [['>=',substr($param['imgassigntime'],0,10).' 00:00:00'], ['<=',substr($param['imgassigntime'],-10,10).' 23:59:59'],'AND'];
        $db = Db::table('manage_assign')
            ->alias('a')
            ->join('skus s','a.sku = s.sku','LEFT')
            ->join('sku_attribute t','a.sku = t.sku','LEFT')
            ->join('sku_handover h','h.sku = a.sku','LEFT')
            ->field('
                a.*,
                s.spu,
                s.name,
                h.type handover_type,
                h.creation_time,
                h.imitation,
                h.realpic,
                h.logo,
                h.quantity,
                h.quantity_unit,
                h.aslength,
                h.aswide,
                h.ashight,
                h.audit_remarks,
                h.research_links,
                h.remarks develop_remarks,
                CASE 
                    h.authorization
                    WHEN 0 THEN "未授权"
                    WHEN 1 THEN "已授权"
                    ELSE "" 
                END authorization_name,
                h.develop_link,
                CASE 
                    a.assign_status 
                    WHEN 1 THEN "待分派"
                    WHEN 2 THEN "已分派"
                    ELSE "" 
                END assign_status_name,
                h.developer,
                CASE 
                    h.production_type 
                    WHEN 1 THEN "资料包"
                    WHEN 2 THEN "样品"
                    ELSE "" 
                END production_type_name
            ');
        !empty($where)&&$db->where($where);
        $db->order('a.id','desc');
        return \app\common\service\ToolService::downOrReturn($db, $param, $titles, $function);
    }

    /**
     * 新/老 编辑/图片审核列表数据
     * @author LSH
     * @return array
     */
    public static function dbGetEditImgAuditList($param, $titles = null, $function = null)
    {
        $where = [];
        $where['a.cancel'] = 0;
        $where['s.status'] = 1; // SKU状态为启用
        $where['a.assign_id'] = isset($param['old'])?0:['<>',0];
        !isset($param['old'])&&$where['a.audit_status'] = ['>=',0];
        !empty($param['developer'])&&$where['b.developer'] = $param['developer'];
        !empty($param['sku'])&&$where['a.sku'] = ['IN',explodeStr($param['sku'])];
        !empty($param['spu'])&&$where['s.spu'] = $param['spu'];
        !empty($param['status'])&&$where['a.audit_status'] = ['IN',explodeStr($param['status'])]; 
        !empty($param['operator'])&&$where['a.operator'] = $param['operator'];   
        !empty($param['importoperator'])&&$where['a.import_operator'] = $param['importoperator'];        
        !empty($param['grade'])&&$where['a.grade'] = $param['grade']; 
        !empty($param['handovertype'])&&$where['h.type'] = ['LIKE','%'.$param['handovertype'].'%']; 

        !empty($param['manufacture_status'])&&$where['a.manufacture_status'] = $param['manufacture_status']; 
        !empty($param['assign_time'])&&$where['a.assign_time'] = [['>=',substr($param['assign_time'],0,10).' 00:00:00'], ['<=',substr($param['assign_time'],-10,10).' 23:59:59'],'AND'];
        !empty($param['finish_time'])&&$where['a.finish_time'] = [['>=',substr($param['finish_time'],0,10).' 00:00:00'], ['<=',substr($param['finish_time'],-10,10).' 23:59:59'],'AND'];
        !empty($param['audittime'])&&$where['a.audit_time'] = [['>=',substr($param['audittime'],0,10).' 00:00:00'], ['<=',substr($param['audittime'],-10,10).' 23:59:59'],'AND'];
        if(!empty($param['assignstatus'])){
            if($param['assignstatus'] == 1) $where['a.operator'] = '';
            if($param['assignstatus'] == 2) $where['a.operator'] = ['<>',''];
        }

        $table = $param['type'] == 'img'? 'manage_img_audit':'manage_edit_audit';
        $db = Db::table($table)
            ->alias('a')
            ->join('skus s','a.sku = s.sku','LEFT')
            ->join('sku_attribute b','a.sku = b.sku','LEFT')
            ->join('sku_handover h','h.sku = a.sku','LEFT')
            ->field('
                a.*,
                s.spu,
                s.name,
                b.developer,
                b.quantity,
                b.quantity_unit,
                b.logo,
                b.develop_link,
                CASE 
                    b.authorization 
                    WHEN 0 THEN "未授权"
                    WHEN 1 THEN "已授权"
                    ELSE "" 
                END authorization,
                h.type handover_type,
                h.remarks handover_remarks,
                h.quantity hquantity,
                h.quantity_unit hquantity_unit,
                h.logo hlogo,
                h.creation_time,
                h.imitation,
                h.realpic,
                h.aslength,
                h.aswide,
                h.ashight,
                h.audit_remarks haudit_remarks,
                h.research_links,
                CASE 
                    h.authorization 
                    WHEN 0 THEN "未授权"
                    WHEN 1 THEN "已授权"
                    ELSE "" 
                END hauthorization,
                CASE 
                    a.audit_status 
                    WHEN 1 THEN "待审核"
                    WHEN 2 THEN "已审核"
                    WHEN 3 THEN "已驳回"
                    ELSE "" 
                END audit_status,
                a.audit_status audit_statusid,
                CASE 
                    a.manufacture_status 
                    WHEN 1 THEN "待确定"
                    WHEN 2 THEN "待制作"
                    WHEN 3 THEN "待审核"
                    WHEN 4 THEN "已驳回"
                    WHEN 5 THEN "已制作"
                    ELSE "" 
                END manufacture_status,
                a.manufacture_status manufacture_statusid,
                CASE 
                    h.production_type 
                    WHEN 1 THEN "资料包"
                    WHEN 2 THEN "样品"
                    ELSE "" 
                END production_type,
                "'.$param['type'].'" ttype ');

        !empty($where)&&$db->where($where);
        $db->order('a.id','desc');
        return \app\common\service\ToolService::downOrReturn($db, $param, $titles, $function);
    }

    /**
     * 新品 图片/描述分派
     * @author LSH
     * @return array
     */
    public static function insertAssignInfo($param,$datas)
    {
        Db::startTrans();
        try{
            $table = $param['type'] == 'img'?'manage_img_audit':'manage_edit_audit';
            $grade = $param['type'] == 'img'?$datas['img_grade']:$param['grade'];

            $data['sku'] = $param['sku'];
            $data['grade'] = $grade;
            $data['operator'] = $param['operator'];
            $data['manufacture_status'] = 2;
            $data['assign_id'] = $param['id'];
            $data['import_operator'] = UID;
            $data['assign_time'] = date('Y-m-d H:i:s',time());
            
            $assign[$param['type'].'_operator'] = $param['operator'];
            $assign[$param['type'].'_grade'] = $grade;
            $assign[$param['type'].'_assign_time'] = date('Y-m-d H:i:s',time());
            $assign[$param['type'].'_assign_operator'] = UID;
            if($datas['img_operator'] || $datas['edit_operator']){
                $assign['assign_status'] = 2;
                $assign['assign_time'] = date('Y-m-d H:i:s',time());
                $assign['assign_operator'] = UID;
            }
            Db::table('manage_assign')->where('id',$param['id'])->update($assign);
            Db::table($table)->insert($data);

            $editor = [];
            $editor[0]['sku'] = $param['sku'];
            $editor[0]['spu'] = Db::table('skus')->where('sku',$param['sku'])->value('spu');
            $editor[0]['operator'] = UID;
            $editor[0]['update_time'] = date('Y-m-d H:i:s',time());
            $editor[0][$param['type'].'_operator'] = $param['operator'];
            ToolModel::dbInsertOrUpdate('setting_editor', $editor);
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            if(isset($param['import'])) return false;
            // echo $e->getMessage();exit;
            returnJson(0,'操作失败');
        }
    }

    /**
     * 样品归还
     * @author LSH
     * @return array
     */
    public static function dbUpdateSampleReturn($param)
    {
        $data['sample_status'] = 2;
        $data['return_people'] = $param['people'];
        $data['return_time'] = date('Y-m-d H:i:s',time());
        return Db::table('manage_manufacture_audit')->where('id',$param['id'])->update($data);
    }

    /**
     * 图片/编辑 审核
     * @author LSH
     * @return array
     */
    public static function dbUpdateMaterialAudit($param,$uid)
    {
        Db::startTrans();
        try{
            $data['auditor'] = $uid;
            $data['manufacture_status'] = ($param['status'] == 3)?4:5;  
            $data['audit_time'] = date('Y-m-d H:i:s',time());
            $data['audit_status'] = $param['status'];
            $data['audit_remarks'] = $param['remarks']; 
            $table = ($param['type'] == 'edit')?'manage_edit_audit':'manage_img_audit';
            Db::table($table)->where('id',$param['id'])->update($data);

            //审核通过 存储空间数据 更新到生产空间
            if($param['status'] == 2){
                if($param['type'] == 'edit'){
                    $hdata = ToolModel::find('sku_handover',['sku'=>$param['sku']]);
                    $uid = ToolModel::getValue('manage_edit_audit',['id'=>$param['id']],'operator');
                    $user = UserModel::getUserById([$uid]);

                    $adata = [];
                    $adata['color'] = $param['fdcolor'];
                    $adata['type'] = $param['fdtype'];
                    $adata['shape'] = $param['fdshape'];
                    $adata['size'] = $param['fdsize'];
                    $adata['pattern'] = $param['fdpattern'];
                    //$adata['developer'] = $hdata['developer'];
                    $adata['bulk'] = $hdata['bulk'];
                    $adata['bulk_unit'] = $hdata['bulk_unit'];
                    $adata['aslength'] = $hdata['aslength'];
                    $adata['aswide'] = $hdata['aswide'];
                    $adata['ashight'] = $hdata['ashight'];
                    $adata['length'] = $hdata['length'];
                    $adata['wide'] = $hdata['wide'];
                    $adata['hight'] = $hdata['hight'];
                    $adata['packaging_film'] = $hdata['packaging_film'];
                    $adata['logo'] = $hdata['logo'];
                    //$adata['develop_link'] = $hdata['develop_link'];
                    $adata['authorization'] = $hdata['authorization'];
                    $adata['quantity'] = $hdata['quantity'];
                    $adata['quantity_unit'] = $hdata['quantity_unit'];
                    $adata['research_links'] = $hdata['research_links'];

                    $adata['imitation'] = $hdata['imitation'];
                    $adata['realpic'] = $hdata['realpic'];

                    if(!Db::table('sku_attribute')->where('sku',$param['sku'])->value('balelength')){
                        $adata['balelength'] = $hdata['aslength'];
                        $adata['balewide'] = $hdata['aswide'];
                        $adata['balehight'] = $hdata['ashight'];
                    }

                    $adata['modification_operator']=$user[$uid];
                    $adata['modification_time']=date('Y-m-d H:i:s');

                    Db::table('sku_attribute')->where('sku',$param['sku'])->update($adata);

                    $i = 0;
                    $mdata = [];
                    $mtype = ['desc_template'=>1,'title_template'=>2,'smt_template'=>3];
                    foreach ($mtype as $key => $val){
                        $mdata[$i]['sku'] = $param['sku'];
                        $mdata[$i]['type'] = $val;
                        $mdata[$i]['value_json'] = $param['fd'.$key];
                        $mdata[$i]['operator'] = $user[$uid];
                        $mdata[$i]['modification_time'] = date('Y-m-d H:i:s',time());
                        $i++;
                    }

                    ToolModel::dbInsertOrUpdate('sku_multiple_attribute', $mdata, ['creation_time']);
                    Db::table('skus')->where('sku',$param['sku'])->update(['modification_time'=>date('Y-m-d H:i:s',time()),'modification_operator'=>$user[$uid]]);
                }

                //分派总状态必须是已分派，编辑和图片都必须审核通过或只有图片分派的情况。把制作状态更新为已制作。
                $assign = ToolModel::find('manage_assign',['sku'=>$param['sku']]);
                $status = 4;
                if($assign['assign_status'] == 2){
                    $ttype = $param['type'] == 'img'?'edit':'img';
                    if(empty($assign[$ttype.'_operator'])){
                        $status = 5;
                    }else{
                        $table = ($param['type'] == 'edit')?'manage_img_audit':'manage_edit_audit';
                        $audit = ToolModel::find($table,['assign_id'=>$assign['id']]);
                        if($audit['manufacture_status'] == 5) $status = 5;
                    }
                }

                //审核驳回 更改交接状态为待制作
                //审核通过 更改交接状态为已完成
                Db::table('sku_handover')->where('sku',$param['sku'])->update(['status'=>$status]);  
            }

            Db::commit();    
            return 1;
        } catch (\Exception $e) {
            echo $e->getMessage();
            Db::rollback();
            return 0;
        }
    }

    /**
     * 获取资料包/样品 审核数据
     * @author LSH
     * @return array
     */
    public static function dbUpdateManufactureAudit($param,$uid)
    {
        Db::startTrans();
        try{
            $data['auditor'] = $uid;
            $data['audit_time'] = date('Y-m-d H:i:s',time());
            $data['status'] = $param['status'];
            $data['remarks'] = $param['remarks'];
            $data['img_grade'] = $param['grade']??'';
            $c = Db::table('manage_manufacture_audit')->where('sku',$param['sku'])->update($data);
            if($c && $param['status'] == 2){
                $insert['sku'] = $param['sku'];
                $insert['operator'] = $uid;
                $insert['creation_time'] = date('Y-m-d H:i:s',time());
                $insert['assign_status'] = 1;
                $insert['img_grade'] = $param['grade']??'';
                Db::table('manage_assign')->insert($insert);
            }

            //审核驳回 更改交接状态为已驳回
            //审核通过 更改交接状态为待制作
            $handover['status'] = ($param['status'] == 3)?2:3;
            $handover['audit_remarks'] = ($param['status'] == 3)?$param['remarks']:'';
            Db::table('sku_handover')->where('sku',$param['sku'])->update($handover);

            Db::commit();    
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            if(isset($param['import'])) return false;
            returnJson(0,'操作失败');
        }
    }
}
